import com.intellij.uiDesigner.core.GridLayoutManager;

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;

public class MainForm {
    private JPanel contentPane;
    private JTextField searchTextField;
    private JList<ImageTextPanel> listPane;
    private DefaultListModel<ImageTextPanel> listModel;
    private List<ImageTextPanel> panels = new ArrayList<>(); // 动态维护一个 ImageTextPanel 的列表
    private CardLayout cardLayout;
    private JPanel cardPanel;

    private final Color Itembtncolor = new Color(116, 118, 121);
    private final Color ItembtnForecolor1 = new Color(255, 255, 255);

    private final Dimension cartSize = new Dimension(280, 30);
    private final Dimension commitBtnSize = new Dimension(60, 30);
    private JButton switchToUserInfoButton;

    // 用户信息和购物车数据
    private String username = "Guest"; // 默认用户名是 Guest
    private List<String> shoppingCart = new ArrayList<>();
    private List<String> orderHistory = new ArrayList<>();

    public MainForm() {
        // 创建窗口
        JFrame frame = new JFrame("CSU外卖");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(450, 700);

        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        int x = (int) ((screenSize.getWidth() - frame.getWidth()) / 2);
        int y = (int) ((screenSize.getHeight() - frame.getHeight()) / 2);
        frame.setLocation(x, y);

        // 创建CardLayout并添加两个面板
        cardLayout = new CardLayout();
        cardPanel = new JPanel(cardLayout);


        // 购物面板
        JPanel shopPanel = createShopPanel();
        cardPanel.add(shopPanel, "Shop");

        // 个人信息面板
        JPanel userInfoPanel = createUserInfoPanel();
        cardPanel.add(userInfoPanel, "UserInfo");

        // 设置主面板
        contentPane = new JPanel();
        contentPane.setLayout(new BorderLayout());
        contentPane.add(cardPanel, BorderLayout.CENTER);


        // 设置窗口内容并显示
        frame.setContentPane(contentPane);
        frame.setVisible(true);

        listPane.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                // 获取点击位置
                int index = listPane.locationToIndex(e.getPoint());
                if (index != -1) {  // 确保点击了有效的项
                    ImageTextPanel clickedPanel = listModel.getElementAt(index);
                    System.out.println("Clicked on: " + clickedPanel.getId());  // 打印点击项的 ID
                    clickedPanel.openPanel(clickedPanel.getId());  // 打开对应的详细面板
                }
            }
        });

        // 创建底部切换按钮
        JPanel buttonPanel = new JPanel();
        switchToUserInfoButton = new JButton("个人信息");
        switchToUserInfoButton.setBackground(Itembtncolor);
        switchToUserInfoButton.setForeground(ItembtnForecolor1);
        switchToUserInfoButton.setBorder(BorderFactory.createLineBorder(Color.black));


        switchToUserInfoButton.setMaximumSize(cartSize);
        switchToUserInfoButton.setMinimumSize(cartSize);
        switchToUserInfoButton.setPreferredSize(cartSize);

        switchToUserInfoButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                cardLayout.show(cardPanel, "UserInfo");
            }
        });

        buttonPanel.add(switchToUserInfoButton);
        contentPane.add(buttonPanel, BorderLayout.SOUTH);
    }


    // 创建购物面板
    private JPanel createShopPanel() {
        JPanel shopPanel = new JPanel();
        shopPanel.setLayout(new BorderLayout());

        // 创建搜索框
        searchTextField = new JTextField(20);
        searchTextField.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        searchTextField.setForeground(Color.BLACK);  // 设置文字颜色
        searchTextField.setBorder(BorderFactory.createLineBorder(Color.GRAY, 1));  // 设置边框
        searchTextField.setMargin(new Insets(5, 10, 5, 10));  // 设置内边距
        searchTextField.setToolTipText("回车搜索");  // 设置提示文本

        searchTextField.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String query = searchTextField.getText().trim();  // 获取搜索框的文本
                search(query);  // 调用搜索功能
            }
        });

        // 创建 JList 并初始化 DefaultListModel<ImageTextPanel>
        listModel = new DefaultListModel<>();  // 明确指定泛型类型为 ImageTextPanel
        listPane = new JList<>(listModel);  // 将 DefaultListModel 传给 JList

        // 创建并添加动态面板
        ImageIcon icon0 = new ImageIcon(getClass().getResource("images/tasiting.jpg"));
        ImageIcon icon1 = new ImageIcon(getClass().getResource("images/huangmenji.jpg"));
        ImageIcon icon2 = new ImageIcon(getClass().getResource("images/th.jpg"));
        ImageIcon icon3 = new ImageIcon(getClass().getResource("images/chayanyuese.jpg"));

        addImageTextPanel("0", icon0, "Item 1 Description");
        addImageTextPanel("1", icon1, "Item 2 Description");
        addImageTextPanel("2", icon2, "Item 2 Description");
        addImageTextPanel("3", icon3, "Item 2 Description");
        addImageTextPanel("3", icon3, "Item 2 Description");
        addImageTextPanel("3", icon3, "Item 2 Description");
        addImageTextPanel("3", icon3, "Item 2 Description");
        addImageTextPanel("3", icon3, "Item 2 Description");
        addImageTextPanel("3", icon3, "Item 2 Description");


        // 使用 ListCellRenderer 适配 ImageTextPanel
        listPane.setCellRenderer(new ListCellRenderer<ImageTextPanel>() {
            @Override
            public Component getListCellRendererComponent(JList<? extends ImageTextPanel> list, ImageTextPanel value, int index, boolean isSelected, boolean cellHasFocus) {
                return value; // 返回自定义面板
            }
        });


        // 将内容添加到购物面板
        shopPanel.add(searchTextField, BorderLayout.NORTH);
        shopPanel.add(new JScrollPane(listPane), BorderLayout.CENTER);
        return shopPanel;
    }

    // 创建个人信息面板
    private JPanel createUserInfoPanel() {
        JPanel userInfoPanel = new JPanel();
        userInfoPanel.setLayout(new BoxLayout(userInfoPanel, BoxLayout.Y_AXIS));

        // 显示用户名和登录按钮
        JPanel userPanel = new JPanel();
        JLabel usernameLabel = new JLabel("用户名: " + username);
        JButton loginButton = new JButton(username.equals("Guest") ? "登入/注册" : "登出");

        loginButton.setMaximumSize(commitBtnSize);
        loginButton.setMinimumSize(commitBtnSize);
        loginButton.setPreferredSize(commitBtnSize);
        loginButton.setBackground(Itembtncolor);
        loginButton.setForeground(ItembtnForecolor1);
        loginButton.setBorder(BorderFactory.createLineBorder(Color.black));
        loginButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (username.equals("")) {
                    // 模拟弹出登录框
                    showLoginDialog(userInfoPanel);
                } else {
                    // 退出登录
                    username = "";
                    loginButton.setText("登入/注册");
                    usernameLabel.setText("用户: " + username);
                }
            }
        });
        userPanel.add(usernameLabel);
        userPanel.add(loginButton);
        userInfoPanel.add(userPanel);

        // 购物车列表
/*        JLabel cartLabel = new JLabel("购物车:");
        userInfoPanel.add(cartLabel);

        JList<String> cartList = new JList<>(shoppingCart.toArray(new String[0]));
        userInfoPanel.add(new JScrollPane(cartList));
*/
        // 订单记录列表
        JLabel orderHistoryLabel = new JLabel("历史订单:");
        userInfoPanel.add(orderHistoryLabel);

        JList<String> orderHistoryList = new JList<>(orderHistory.toArray(new String[0]));
        orderHistoryList.setBackground(new Color(223, 225, 229));
        userInfoPanel.add(new JScrollPane(orderHistoryList));

        // 下单按钮
/*        JButton orderButton = new JButton("下单");
        orderButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 模拟下单操作
                if (!shoppingCart.isEmpty()) {
                    orderHistory.add("Order: " + shoppingCart);
                    shoppingCart.clear();
                    JOptionPane.showMessageDialog(userInfoPanel, "成功下单！");
                } else {
                    JOptionPane.showMessageDialog(userInfoPanel, "购物车已清空!");
                }
                // 更新订单记录和购物车显示
//                cartList.setListData(shoppingCart.toArray(new String[0]));
                orderHistoryList.setListData(orderHistory.toArray(new String[0]));
            }
        });

        userInfoPanel.add(orderButton);
*/
        // 添加返回按钮，返回到购物面板
        JButton backButton = new JButton("主页");

        backButton.setMaximumSize(commitBtnSize);
        backButton.setMinimumSize(commitBtnSize);
        backButton.setPreferredSize(commitBtnSize);
        backButton.setBackground(Itembtncolor);
        backButton.setForeground(ItembtnForecolor1);
        backButton.setBorder(BorderFactory.createLineBorder(Color.black));
        backButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                cardLayout.show(cardPanel, "Shop");
            }
        });
        userInfoPanel.add(backButton);

        return userInfoPanel;
    }

    // 登录框
    private void showLoginDialog(JPanel parentPanel) {
        JTextField usernameField = new JTextField(15);
        JPasswordField passwordField = new JPasswordField(15);

        JPanel loginPanel = new JPanel(new GridLayout(3, 2));
        loginPanel.add(new JLabel("用户名:"));
        loginPanel.add(usernameField);
        loginPanel.add(new JLabel("密码:"));
        loginPanel.add(passwordField);
        int option = JOptionPane.showConfirmDialog(parentPanel, loginPanel, "登入", JOptionPane.OK_CANCEL_OPTION);

        if (option == JOptionPane.OK_OPTION) {
            // 假设用户名和密码验证通过
            String usernameInput = usernameField.getText();
            username = usernameInput.isEmpty() ? "Guest" : usernameInput;

            // 更新个人信息面板上的用户名
            JPanel userPanel = (JPanel) parentPanel.getComponent(0);
            JLabel usernameLabel = (JLabel) userPanel.getComponent(0);
            usernameLabel.setText("用户: " + username);

            // 更新按钮文本
            JButton loginButton = (JButton) userPanel.getComponent(1);
            loginButton.setText("登出");
        }
    }

    // 添加新的 ImageTextPanel
    private void addImageTextPanel(String id, ImageIcon imageIcon, String text) {
        ImageTextPanel panel = new ImageTextPanel(id, imageIcon, text, contentPane);
        panels.add(panel); // 将新面板添加到列表中
        listModel.addElement(panel); // 添加到 JList 中
    }

    private void search(String query) {
        DefaultListModel<ImageTextPanel> filteredModel = new DefaultListModel<>();  // 创建一个新的列表模型来存储搜索结果

        // 遍历原列表，筛选出包含输入查询内容的项
        for (int i = 0; i < listModel.getSize(); i++) {
            ImageTextPanel item = listModel.getElementAt(i);
            if (item.getText().toLowerCase().contains(query.toLowerCase())) {  // 不区分大小写的匹配
                filteredModel.addElement(item);  // 添加匹配的项
            }
        }

        // 更新 JList 显示的内容
        listPane.setModel(filteredModel);
    }

    public static void main(String[] args) {
        new MainForm();
    }

    {
// GUI initializer generated by IntelliJ IDEA GUI Designer
// >>> IMPORTANT!! <<<
// DO NOT EDIT OR ADD ANY CODE HERE!
        $$$setupUI$$$();
    }

    /**
     * Method generated by IntelliJ IDEA GUI Designer
     * >>> IMPORTANT!! <<<
     * DO NOT edit this method OR call it in your code!
     *
     * @noinspection ALL
     */
    private void $$$setupUI$$$() {
        final JPanel panel1 = new JPanel();
        panel1.setLayout(new GridLayoutManager(1, 1, new Insets(0, 0, 0, 0), -1, -1));
    }
}
